#include<bits/stdc++.h>
#define IOS ios::sync_with(false), cin.tie(0), cout.tie(0)
#define int long long
#define endl "\n"
using namespace std;
map<int, vector<int>>mp;
map<int, set<int>>mp2;
map<int, vector<int>>per;

bool a[10010][1000];

signed main() {
	int n, m, ret = 0;
	cin >> n >> m;
	for(int i = 1; i <= n; ++ i ) {
		int k;
		cin >> k;
		for(int j = 1; j <= k; ++ j ) {
			int x;
			cin >> x;
			if(x < 1000)
			a[i][x] = 1;
			else {
				mp2[i].insert(x);
			}
		}
	}
	
	int q;
	cin >> q;
	while(q -- ) {
		int x, y;
		ret = 0;
		cin >> x >> y;
		for(int i = 1; i <= n; ++ i ) {
			int gs = 0;
			if(x < 1000) {
				if(a[i][x]) {
					gs ++ ;
				}
			} else {
				if(mp2[i].find(x) != mp2[i].end()) {
					gs ++ ;
				}
			}
			if(y < 1000) {
				if(a[i][y]) {
					gs ++ ;
				}
			} else {
				if(mp2[i].find(y) != mp2[i].end()) {
					gs ++ ;
				}
			}
			if(gs == 2) {
				ret ++ ;
			}
		}
		cout << ret << endl;
	}
//	cout << ret << endl;
	return 0;
}

